var scpClient = require('scp2')
var Client = require('ssh2').Client
const ora = require('ora')
var path = require('path')
const chalk = require('chalk')
const fs = require('fs')

var appDir = path.dirname(require.main.filename)
appDir = path.join(appDir, '../')
configPath = path.join(appDir, '../') + '/config.json'
config = fs.readFileSync(configPath, 'utf8')
config = JSON.parse(config)
config = config[process.argv[2]]
distPath = process.argv[3]
const spinner = ora(
  '正在发布到' +
    (process.argv[2] === 'prod' ? '生产' : '测试') +
    '服务器...'
)
sourcePath = appDir + 'dist'

var conn = new Client()
conn
  .on('ready', function () {
    // rm 删除dist文件，\n 是换行 换行执行
    conn.exec('rm -rf ' + distPath + '/*', function (
      err,
      stream
    ) {
      if (err) throw err
      stream
        .on('close', function (code, signal) {
          // 在执行shell命令后，把开始上传部署项目代码放到这里面
          spinner.start()
          scpClient.scp(
            sourcePath, {
              host: config.host,
              port: config.port,
              username: config.username,
              password: config.password,
              path: distPath
            },
            function (err) {
              spinner.stop()
              if (err) {
                console.log(chalk.red('发布失败.\n'))
                throw err
              } else {
                console.log(
                  chalk.green(
                    'Success! 成功发布到' +
                      (process.argv[2] === 'prod'
                        ? '生产'
                        : '测试') +
                      '服务器! \n'
                  )
                )
              }
            }
          )
          conn.end()
        })
        .on('data', function (data) {
          console.log('STDOUT: ' + data)
        })
        .stderr.on('data', function (data) {
          console.log('STDERR: ' + data)
        })
    })
  })
  .connect({
    host: config.host,
    port: config.port,
    username: config.username,
    password: config.password
  })
